﻿using System;
using System.CodeDom.Compiler;
using System.Windows.Forms;
using System.Windows.Threading;

public static class UIDispatcher
{
    private static Control uiControl;
    private static Dispatcher dispatcher;
    private static Action<Action> executor = action => action();

    public static void Initialize(Control control)
    {
        dispatcher = Dispatcher.CurrentDispatcher;
        executor = action =>
        {
            if (dispatcher.CheckAccess())
                action();
            else dispatcher.BeginInvoke(action);
        };
        uiControl = control ?? throw new ArgumentNullException(nameof(control));
    }

    public static void Invoke(Action action)
    {
        if (uiControl == null)
            throw new InvalidOperationException("UI dispatcher is not initialized.");

        if (uiControl.InvokeRequired)
        {
            uiControl.Invoke(action);
        }
        else
        {
            action();
        }
    }

    public static void BeginInvoke(Action action)
    {
        if (uiControl == null)
            throw new InvalidOperationException("UI dispatcher is not initialized.");

        uiControl.BeginInvoke(action);

    }
    public static void OnUIThread(this Action action)
    {
        executor(action);
    }
}
